const express = require('express')
const common = require('../libs/common')
const mysql = require('mysql')

const db = mysql.createPool({
	host: 'localhost',
	user: 'root',
	password: 'root',
	database: 'learn',
})
module.exports = function(){

	let router = express.Router()
	//检查登录状态
	router.use((req,res,next) => {
		if(!req.session['admin_id'] && req.url != '/login'){
			res.redirect('/admin/login')
		}else{
			next()
		}
	})
	router.get('/login',(req,res) => {
		res.render('admin/login.ejs',{})
	})
	router.post('/login',(req, res) => {
		console.log(req.body)
		var username = req.body.username
		var password = common.md5(req.body.password)
		db.query(`SELECT * FROM admin_table WHERE username='${username}'`,(err,data) => {
			if(err){
				console.error(err)
				res.status(500).send('database error').end()
			}else{
				if(data.length == 0){
					res.status(400).send('no this admin').end()
				}else{
					if(data[0].password == password){
						// res.send('登录成功').end()
						req.session['admin_id'] = data[0].ID
						res.redirect('/admin/')
					}else{
						res.status(400).send('密码错误').end()
					}
				}
			}
		})
		
		// res.send('我是admin').end()
	})
	router.get('/',(req,res) => {
		res.render('admin/index.ejs',{})
	})
	router.get('/banner',(req,res) => {
		
		switch(req.query.act){
			case 'del':
				db.query(`delete from banner_table WHERE ID='${req.query.id}'`,(err,data)=>{
					if(err){
						res.status(500).send('database err').end()
					}else{
						res.redirect('/admin/banner')
					}
				})
			break;
			case 'change':
			break;
			default:
				db.query(`select * from banner_table`,(err,banners)=>{
				if(err){
					res.status(500).send('database err').end()
				}else{
					res.render('admin/banner.ejs',{banners})
				}
			})
			break;
		}
		
	})
	router.post('/banner',(req,res) => {
		let title = req.body.title;
		let description = req.body.description;
		let href = req.body.href;
		if(!title || !description || !href){
			res.status(400).send('数据不能为空').end()
		}else{
			db.query(`insert into banner_table (title, description, href) value('${title}', '${description}', '${href}')`, (err,data) => {
				if(err){
					res.status(500).send('database err').end()
				}else{
					res.redirect('/admin/banner')
				}
			})
		}
	})
	return router;
}